<template>
  <div>
    <div id="cesiumContainer" ref="cesiumContainerRef"></div>
    <!-- 悬浮弹窗 -->
    <div
      v-show="equipmentInfo.show"
      class="chen-infomationAlert"
      :style="{
        left: equipmentInfo.x - 16 + 'px',
        top: equipmentInfo.y + 8 + 'px'
      }"
    >
      <div class="bgTop"></div>
      <div class="bgCenter" v-html="equipmentInfo.content"></div>
      <div class="bgBottom"></div>
    </div>
    <!-- 详情弹窗 -->
    <div
      class="chen-infomationPop"
      v-if="pointIframe.show"
      ref="drag"
      :style="{ left: pointIframe.x + 'px', top: pointIframe.y + 'px' }"
    >
      <div class="bgTop">
        <span>{{ pointIframe.title }}</span>
        <span class="close" @click="pointIframe.show = false">×</span>
      </div>
      <div class="bgCenter">
        <!-- <iframe :src="pointIframe.url" frameborder="0"></iframe> -->
        <div class="content" v-if="pointIframe.pointType == '监控'">
          <video controls src="" type=""></video>
        </div>
        <div class="content" v-else>
          <p>名称2：{{ pointIframe.title }}</p>
          <p>所属位置：湖南省浏阳市</p>
          <p>所属公司：-</p>
          <p>描述：-</p>
          <p>材料：-</p>
          <p>建筑：-</p>
          <p>关系：-</p>
        </div>
      </div>
      <div class="bgBottom"></div>
    </div>
    <!-- 坐标信息 -->
    <div class="pointInfo">
      <span>x: {{ point.x.toFixed(5) }}</span>
      <span>y: {{ point.y.toFixed(5) }}</span>
      <span>z: {{ point.z }}</span>
    </div>
    <!-- 测距，测面，测高工具面板 -->
    <div class="toolTip"></div>
    <!-- 测量参数录入弹窗 -->
    <VueDragResize
      :w="0"
      :h="0"
      :z="0"
      :x="700"
      :y="300"
      :isResizable="false"
      @clicked="clickHandle"
    >
      <div class="addInfoPop" v-show="addPopInfo.popShow">
        <span class="close" @click="closeAddPop">×</span>
        <div class="popTop">
          <span>{{ addPopInfo.title }}</span>
        </div>
        <div class="popCenter">
          <a-form ref="formRef" :model="addPopInfo">
            <a-form-item
              label="名称"
              class="lang_input"
              name="name"
              :rules="[
                {
                  required: true,
                  message: '请输入名称!'
                }
              ]"
            >
              <a-input
                v-model:value="addPopInfo.name"
                placeholder="请输入名称"
              ></a-input>
            </a-form-item>
            <a-form-item
              label="地址"
              class="lang_input"
              name="address"
              :rules="[
                {
                  required: true,
                  message: '请输入地址!'
                }
              ]"
            >
              <a-input
                v-model:value="addPopInfo.address"
                placeholder="请输入地址"
              ></a-input>
            </a-form-item>
            <a-form-item
              label="图标"
              name="iconLabel"
              class="selectIcon"
              :rules="[
                {
                  required: true,
                  message: '请选择图标!'
                }
              ]"
              v-if="addPopInfo.type == 'point'"
            >
              <a-select
                v-model:value="addPopInfo.iconLabel"
                placeholder="请选择图标"
              >
                <a-select-option
                  v-for="option in iconOptions"
                  :key="option.value"
                  :value="option.name"
                >
                  <img :src="option.url" alt="" class="imageIcon" />
                  <span>{{ option.name }}</span>
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              label="图标高度"
              name="iconHeight"
              :rules="[
                {
                  required: true,
                  message: '请输入图标高度!'
                }
              ]"
              v-if="addPopInfo.type == 'point'"
            >
              <a-input
                v-model:value="addPopInfo.iconHeight"
                placeholder="高度建议设置15"
              ></a-input>
            </a-form-item>
            <a-form-item
              label="经度"
              name="lon"
              :rules="[
                {
                  required: true,
                  message: '请输入经度!'
                }
              ]"
              v-if="addPopInfo.type == 'point'"
            >
              <a-input
                v-model:value="addPopInfo.lon"
                placeholder="请输入经度"
              ></a-input>
            </a-form-item>
            <a-form-item
              label="纬度"
              name="lat"
              :rules="[
                {
                  required: true,
                  message: '请输入纬度!'
                }
              ]"
              v-if="addPopInfo.type == 'point'"
            >
              <a-input
                v-model:value="addPopInfo.lat"
                placeholder="请输入纬度"
              ></a-input>
            </a-form-item>
            <!-- 监控才能设置弹窗高宽度 -->
            <a-form-item
              label="弹窗宽度"
              name="lat"
              v-if="
                addPopInfo.type == 'point' && addPopInfo.iconLabel == '监控'
              "
            >
              <a-input
                v-model:value="addPopInfo.videoWidth"
                placeholder="弹窗宽度(px)"
              ></a-input>
            </a-form-item>
            <a-form-item
              label="弹窗高度"
              name="lat"
              v-if="
                addPopInfo.type == 'point' && addPopInfo.iconLabel == '监控'
              "
            >
              <a-input
                v-model:value="addPopInfo.videoHeight"
                placeholder="弹窗高度(px)"
              ></a-input>
            </a-form-item>
          </a-form>
        </div>
        <div class="popBottom">
          <button @click="addPopData">
            {{ addPopInfo.type == 'point' ? '确认' : '新增' }}
          </button>
        </div>
      </div>
    </VueDragResize>
  </div>
</template>

<script lang="ts">
import { toRefs, reactive, ref, onMounted, watch, nextTick } from 'vue';
import * as Cesium from 'cesium';
import viewMap from '../utils/view';
import { loading, getUUID } from '../utils';
import { useRoute } from 'vue-router';
// import tiles from '../../public/cesium/Assets/znyhosgb/tileset.json';
import http from '../../src/utils/request';
import { message } from 'ant-design-vue';
// @ts-ignore
import VueDragResize from 'vue-drag-resize/src';
import dayjs from 'dayjs';

export default {
  components: { VueDragResize },
  props: {
    text: {
      type: String
    },
    iconOptions: {
      type: Object
    }
  },
  setup(props: { text: string; speed: number | undefined } | any) {
    const route = useRoute();
    const drag = ref();
    const cesiumContainerRef = ref();
    const formRef = ref();
    let viewer = null as unknown as Cesium.Viewer;
    let cesium = null as unknown as viewMap;
    let movePoint = null as any;
    var sceneObject = {
      fourColorArray: [] as any[],
      areaArray: [] as any[]
    };
    const pointDataSource = new Map<string, Cesium.CustomDataSource>();

    const data = reactive({
      point: {
        x: 0,
        y: 0,
        z: 0
      },
      // 弹窗信息
      equipmentInfo: {
        show: false,
        content: ``,
        x: 0,
        y: 0
      },
      pointIframe: {
        type: '',
        pointType: '',
        show: false,
        url: '',
        title: '',
        x: 0,
        y: 0
      },
      // 存储弹窗信息
      addPopInfo: {
        popShow: false,
        title: '新增弹窗',
        width: 600,
        height: 0,
        type: 'point',
        name: '',
        address: '',
        iconLabel: '区域点位',
        iconHeight: 15 as number, // 图标高度
        lon: 0 as number, // 图标经度
        lat: 0 as number, // 图标纬度
        videoWidth: 0 as number, // 监控弹窗宽度
        videoHeight: 0 as number, // 监控弹窗高度
        position: [] as any,
        measureValue: null as any,
        measureType: ''
      }
    });
    onMounted(() => {
      nextTick(() => {
        loadMap();
      });
    });

    watch(
      data.addPopInfo,
      (val: any) => {
        // console.log(val);
        // console.log(data.addPopInfo.popShow);
        if (
          data.addPopInfo.popShow == true &&
          data.addPopInfo.type == 'point'
        ) {
          if (typeof val.lon != 'number') {
            message.warning('经纬度以及高度请输入数字类型！！');
            return;
          }
          let lon = parseFloat(val.lon);
          let lat = parseFloat(val.lat);
          let iconHeight = parseFloat(val.iconHeight);
          // 实时修改自定义图标
          if (movePoint && lon && lat && iconHeight) {
            // console.log(movePoint);
            movePoint.label.text = val.name;
            // 使用 find 方法取出具有特定名称的对象
            const foundObject = props.iconOptions.find(
              (obj: any) => obj.name === val.iconLabel
            );
            movePoint.billboard.image = foundObject?.url;
            movePoint.position = Cesium.Cartesian3.fromDegrees(
              lon,
              lat,
              iconHeight
            );
          }
        }
      },
      { deep: true }
    );

    watch(
      () => props.text,
      (val: any) => {
        console.log(val);
      }
    );

    watch(
      () => route.name,
      (val: any) => {
        console.log(val);
      }
    );

    // 加载cesium地图
    const loadMap = async () => {
      cesium = await new viewMap(
        cesiumContainerRef.value,
        {},
        (view: Cesium.Viewer) => {
          viewer = view;
          // console.log(view);
          if (!viewer) {
            loading.show(
              '加载地图失败 &nbsp; 访问过期 &nbsp; 请联系开发管理！',
              cesiumContainerRef.value
            );
          } else {
            loading.hide();
            flyto(113.7007, 27.939955);

            props.iconOptions
              .concat([{ name: '移动点位' }])
              .forEach((item: any) => {
                const cds = new Cesium.CustomDataSource(item.name);
                pointDataSource.set(item.name, cds);
                viewer.dataSources.add(cds);
              });
          }
        }
      );

      setTimeout(() => {
        // 点击事件
        cesium.eventHandling(
          'MOUSE_MOVE',
          (e: {
            show: boolean;
            content: string;
            x: number;
            y: number;
            entityVal: any;
          }) => {
            // console.log(e.entityVal._id);
            // 悬浮变色
            // if (sceneObject.fourColorArray.length != 0) {
            //   sceneObject.fourColorArray.forEach((item: any) => {
            //     if (item._id == e.entityVal._id) {
            //       // console.log(item);
            //       item.polygon.material =
            //         Cesium.Color.fromCssColorString('#ff550000').withAlpha(0.8);
            //     } else {
            //       let color = item._id.split('+')[1];
            //       item.polygon.material =
            //         Cesium.Color.fromCssColorString(color).withAlpha(0.8);
            //     }
            //   });
            // }
            data.equipmentInfo = e;
          }
        );

        cesium.eventHandling('LEFT_CLICK', (e: any) => {
          console.log(e);
          data.pointIframe = e;
          if (e.show) {
            setTimeout(() => {
              dragFunction(drag.value);
            }, 300);
          }
        });
        // 添加倾斜摄影
        cesium.load3DTileset('/model/znyhosgb/tileset.json', 16, -80, () => {
          // viewer.zoomTo(data)
          // 添加label文字
          fetch(`./json/区块标签.json`)
            .then((res) => res.json())
            .then((res) => {
              // console.log(res);
              res.features.forEach((item: any, index: any) => {
                addLabel(
                  '区块标签-' + (index + 1),
                  item.name,
                  item.labelPostion
                );
              });
            });
        });
        // 获取点位坐标
        cesium.getPosition(
          (coordinate: { x: number; y: number; z: number }) => {
            data.point = coordinate;
          }
        );
      }, 3000);
      (window as any).cesium = cesium;
    };

    // 拖拽
    const dragFunction = (el: HTMLElement) => {
      document.removeEventListener('mousedown', () => {});
      document.removeEventListener('mouseup', () => {});
      el.style.position = 'absolute';
      let offsetX: number = 0;
      let offsetY: number = 0;
      el.addEventListener('mousedown', function (event: any) {
        if (event.button == 0 && el) {
          const lexObj: any = getComputedStyle(el);
          offsetX =
            event.pageX - el.offsetLeft + parseInt(lexObj['margin-left']);
          offsetY =
            event.pageY - el.offsetTop + parseInt(lexObj['margin-right']);
          const move = function (event: any) {
            if (el) {
              let x = event.pageX - offsetX;
              let y = event.pageY - offsetY;
              if (x < 0) {
                x = 0;
              } else if (
                x >
                document.documentElement.clientWidth - el.offsetWidth
              ) {
                x = document.documentElement.clientWidth - el.offsetWidth;
              }
              if (y < 0) {
                y = 0;
              } else if (
                y >
                document.documentElement.clientHeight - el.offsetHeight
              ) {
                y = document.documentElement.clientHeight - el.offsetHeight;
              }
              data.pointIframe.x = x;
              data.pointIframe.y = y;
              // el.style.left = x + 'px';
              // el.style.top = y + 'px';
            }
            return false;
          };
          document.addEventListener('mousemove', move);
          const stop = function () {
            document.removeEventListener('mousemove', move);
            document.removeEventListener('mouseup', stop);
          };
          document.addEventListener('mouseup', stop);
        }
        return false;
      });
    };

    // 添加poi标点（广告牌）
    const addPoint = async (name: string, boolean: boolean, imgUrl: string) => {
      // const point = viewer.dataSources.getByName(name);
      const point = pointDataSource.get(name)?.entities.values || [];
      // console.log(point)
      let pointArray = [] as any[];
      let dataArr = [] as any[]; // 用于存储未自定义点位数据

      if (point.length > 0) {
        dataArr = point.filter((item: any) => {
          let str = item.id.split('-')[0];
          return str != '移动点位';
        });
      }
      // console.log(dataArr);
      // 地图已存在即显示隐藏，不存在即新增
      if (dataArr.length > 0) {
        point.forEach((item: any) => {
          item.show = boolean;
        });
        // pointLocal = pointLocal || point[0];
        // if (boolean) viewer.flyTo(pointLocal);
      } else {
        if (boolean) {
          // 若第一次勾选添加，则需获取数据
          await fetch(`./json/${name}.json`)
            .then((res) => res.json())
            .then((res) => {
              pointArray = res.features;
            });
          // const customDataSource = new Cesium.CustomDataSource(name);
          // await viewer.dataSources.add(customDataSource);
          pointArray.forEach((item: any, index: any) => {
            pointDataSource.get(name)?.entities.add({
              show: true,
              id: name + '-' + (index + 1),
              name: { ...item.properties, TYPE: 'POINT' },
              billboard: {
                // image: './iconImg/textImg.png', // 默认图标
                image: imgUrl, // 默认图标
                scale: 1.0, // 图标缩放比例
                // height:-10,
                // scaleByDistance: new Cesium.NearFarScalar(0, 1, 0, 0.4),
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM, // 将广告牌底部与位置对齐
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                disableDepthTestDistance: Number.POSITIVE_INFINITY, // 漂移bug Number.POSITIVE_INFINITY
                // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, // 解决地形遮挡
                // pixelOffset: new Cesium.Cartesian2(0, -15),
                // eyeOffset: new Cesium.Cartesian3(
                //   0.0,
                //   name !== '区域点位' ? item.properties.O_Alt : 15,
                //   0
                // ),
                distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                  0.0,
                  1000000.0
                ),
                scaleByDistance: new Cesium.NearFarScalar(1e2, 1, 1e4, 0.2)
              },
              label: {
                text: item.properties.NAME, // 显示的文字
                font: '16px Helvetica', // 字体设置
                fillColor: Cesium.Color.WHITE,
                outlineColor: Cesium.Color.SKYBLUE,
                outlineWidth: 2,
                style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                // eyeOffset: new Cesium.Cartesian3(
                //   0.0,
                //   name !== '区域点位' ? item.properties.O_Alt : 15,
                //   -30.0
                // ),
                pixelOffset: new Cesium.Cartesian2(0, -45), // 文字偏移量
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
                scaleByDistance: new Cesium.NearFarScalar(1e2, 1, 2e3, 0.0)
              },
              // position: Cesium.Cartesian3.fromDegrees(
              //   item.geometry.coordinates[0],
              //   item.geometry.coordinates[1],
              // )
              position: Cesium.Cartesian3.fromDegrees(
                item.properties.X,
                item.properties.Y,
                name !== '区域点位' ? item.properties.O_Alt : 15
              ) // 手动点位
            });
          });
        }
      }
    };

    // 添加生产数量详情弹窗
    const addProductPoint = async (
      name: string,
      dataArr: any[],
      bool: boolean
    ) => {
      const point = viewer.dataSources.getByName(name);
      console.log(point, '>>>>');
      // 显示隐藏name图层
      point.forEach((item: any) => {
        item.show = bool;
      });
      // 若实体面板对象中没有数据则新增
      if (point.length == 0) {
        const customDataSource = new Cesium.CustomDataSource(name);
        await viewer.dataSources.add(customDataSource);
        dataArr.forEach((item: any) => {
          // 进度详情实体
          let sheduleOption = entiteOption(
            item.name + '-' + getUUID(),
            './iconImg/baxTip.png',
            item,
            `${item.name}: ${item.finishVal} / ${item.planVal}`,
            item.X,
            item.Y
          );
          // console.log(sheduleOption);
          customDataSource.entities.add(sheduleOption);
        });
      } else {
        // 若对应name实体中实体已经有数据，则做响应数据处理
        let pointRenderData = point[0].entities.values;
        // 修改数据处理
        dataArr.forEach((item: any) => {
          let index = pointRenderData.some((dataObj: any) => {
            if (item.name == dataObj.name.name) {
              console.log(item.name);
              dataObj.show = bool;
              dataObj.label.text = `${item.name}: ${item.finishVal} / ${item.planVal}`;
            }
            // 返回是否存在这个name标签
            return dataObj.name?.name == item.name;
          });
          console.log(index);
          // 如果面板中不存在dataArr中的某个的name则新增
          if (!index) {
            // 进度详情实体
            let sheduleOption = entiteOption(
              item.name + '-' + getUUID(),
              './iconImg/baxTip.png',
              item,
              `${item.name}: ${item.finishVal} / ${item.planVal}`,
              item.X,
              item.Y
            );
            point[0].entities.add(sheduleOption);
          }
        });
        // 若数据中没有传入对应点位name，则隐藏标点
        pointRenderData.forEach((el: any) => {
          let isShow = dataArr.some((item: any) => {
            return el.name?.name == item.name;
          });
          el.show = isShow;
        });
      }
    };
    // 生成地图信息窗口实体
    const entiteOption = (
      id: string,
      imgUrl: string,
      content: any,
      labelText: string, // 标签文字
      lon: any,
      lat: any,
      height = 15
    ) => {
      let option = {
        show: true,
        id: id,
        name: { ...content, TYPE: 'SCHEDULE' },
        label: {
          text: labelText, // 显示的文字
          font: '30px Helvetica', // 字体设置
          fillColor: Cesium.Color.WHITE,
          outlineColor: Cesium.Color.WHITE,
          // outlineWidth: 2,
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          // eyeOffset: new Cesium.Cartesian3(
          //   0.0,
          //   name !== '区域点位' ? item.properties.O_Alt : 15,
          //   -30.0
          // ),
          pixelOffset: new Cesium.Cartesian2(0, 10), // 文字偏移量
          disableDepthTestDistance: Number.POSITIVE_INFINITY,
          scaleByDistance: new Cesium.NearFarScalar(1e2, 1, 2e3, 0.0)
        },
        billboard: {
          image: imgUrl, // 默认图标
          scale: 0.5, // 图标缩放比例
          // height:-10,
          // scaleByDistance: new Cesium.NearFarScalar(0, 1, 0, 0.4),
          verticalOrigin: Cesium.VerticalOrigin.CENTER, // 将广告牌底部与位置对齐
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          disableDepthTestDistance: Number.POSITIVE_INFINITY, // 漂移bug Number.POSITIVE_INFINITY
          // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, // 解决地形遮挡
          // pixelOffset: new Cesium.Cartesian2(0, -15),
          // eyeOffset: new Cesium.Cartesian3(
          //   0.0,
          //   name !== '区域点位' ? item.properties.O_Alt : 15,
          //   0
          // ),
          distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
            0.0,
            1000000.0
          ),
          scaleByDistance: new Cesium.NearFarScalar(1e2, 1, 2e3, 0.0)
        },
        // position: Cesium.Cartesian3.fromDegrees(
        //   item.geometry.coordinates[0],
        //   item.geometry.coordinates[1],
        // )
        position: Cesium.Cartesian3.fromDegrees(lon, lat, height) // 手动点位
      };
      return option;
    };

    // 添加贴地四色图区域
    const addColorSegment = (
      id: string, // 标识
      areaArray: any[], // 点位数据
      color: string, // 颜色
      isVisible: boolean //显示隐藏
      // height = 50 // 高度
    ) => {
      // console.log(id, isVisible, height);
      // // 使用 some() 方法检查对象数组中是否存在具有特定 id 的对象
      var exists = sceneObject.fourColorArray.some(function (obj) {
        return obj.id === id;
      });
      // 判断是否存在，如果存在区域块，则显示隐藏，不存在则新增
      if (exists) {
        sceneObject.fourColorArray.forEach((item: any) => {
          if (item.id == id) {
            item.show = isVisible;
          }
        });
        return;
      }
      if (isVisible) {
        // 使用entity实体添加区域块
        let polygon = viewer.entities.add({
          id: id,
          polygon: {
            hierarchy: new Cesium.PolygonHierarchy(
              Cesium.Cartesian3.fromDegreesArray(areaArray)
            ),
            material: Cesium.Color.fromCssColorString(color).withAlpha(0.8),
            classificationType: Cesium.ClassificationType.BOTH
            // height: height
          },
          show: true
        });
        // 保存实例
        sceneObject.fourColorArray.push(polygon);
      }
    };

    // 添加区块
    const addArea = (
      id: string, // 标识
      areaArray: any[], // 点位数据
      color: string, // 颜色
      isVisible: boolean, //显示隐藏
      height = 60 // 高度
    ) => {
      // console.log(id);
      // 使用 some() 方法检查对象数组中是否存在具有特定 id 的对象
      var exists = sceneObject.areaArray.some(function (obj) {
        return obj.id === id;
      });
      // 判断是否存在，如果存在区域块，则显示隐藏，不存在则新增
      if (exists) {
        sceneObject.areaArray.forEach((item: any) => {
          if (item.id == id) {
            item.show = isVisible;
          }
        });
        return;
      }
      if (isVisible) {
        // 使用传入的颜色参数创建几何实例
        var customColorAttribute =
          Cesium.ColorGeometryInstanceAttribute.fromColor(
            Cesium.Color.fromCssColorString(color).withAlpha(0.8)
          );
        // 创建并添加多个矩形实体到场景中(添加几何体方法)
        // console.log(areaArray);
        let instance = new Cesium.GeometryInstance({
          geometry: new Cesium.PolygonGeometry({
            polygonHierarchy: new Cesium.PolygonHierarchy(
              Cesium.Cartesian3.fromDegreesArray(areaArray)
            ),
            vertexFormat: Cesium.PerInstanceColorAppearance.VERTEX_FORMAT,
            // height: height,// 区块所在高度，不能与下方extrudedHeight一起使用
            perPositionHeight: true, // 指定每个位置的高度
            extrudedHeight: height, // 设置统一的高度
            // closeBottom: false, // 若为false，则去除关闭底部填充属性
            closeTop: false, // 若为false，则去除关闭顶部填充属性
            // arcType: Cesium.ArcType.NONE
            textureCoordinates: new Cesium.PolygonHierarchy(
              Cesium.Cartesian3.fromDegreesArray([113.7, 27.94237]),
              []
            )
          }),
          attributes: {
            color: customColorAttribute // 指定颜色
          }
        });

        let primitive = new Cesium.Primitive({
          geometryInstances: instance,
          appearance: new Cesium.PerInstanceColorAppearance({
            flat: true,
            translucent: true
          })
        });
        // 赋值id
        (primitive as any)['id'] = id;
        primitive.show = true;
        sceneObject.areaArray.push(primitive);
        // 场景中添加
        viewer.scene.primitives.add(primitive);
      }
    };

    // 添加文字label
    const addLabel = (id: string, text: string, point: any[]) => {
      // 创建文字标签
      viewer.entities.add({
        id: id,
        position: Cesium.Cartesian3.fromDegrees(point[0], point[1]),
        show: true,
        label: {
          text: text,
          font: '26px Helvetica',
          fillColor: Cesium.Color.WHITE,
          outlineColor: Cesium.Color.BURLYWOOD,
          outlineWidth: 2,
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          // horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          // verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          eyeOffset: new Cesium.Cartesian3(0.0, 40, 0.0),
          // // heightReference: Cesium.HeightReference.NONE, // 解决地形遮挡,不随视角拉远而变化
          pixelOffset: new Cesium.Cartesian2(0, 0), // 调整文字位置
          disableDepthTestDistance: Number.POSITIVE_INFINITY,
          scaleByDistance: new Cesium.NearFarScalar(1e2, 1.5, 5e3, 0.0)
        }
      });
    };

    // 测距，测面，测高
    const calculateTool = (type: string) => {
      // 点击工具将弹窗转为测量信息窗口
      data.addPopInfo.type = 'measure';
      data.addPopInfo.measureType = type;
      data.addPopInfo.title = '新增' + type + '弹窗';
      // 重置弹窗信息
      formRef.value.resetFields();
      // 生成一个测量唯一id,用于代表生成的线或者面实体
      let calculateId = getUUID();
      switch (type) {
        case '测距':
          cesium.drawLineMeasureGraphics(
            true,
            calculateId,
            (pos: any, val: any) => {
              console.log(pos, '>>>>>>>>>>', val);
              data.addPopInfo.position = pos;
              data.addPopInfo.measureValue = val;
              // 画完图形后打开弹窗
              data.addPopInfo.popShow = true;
              console.log(data.addPopInfo.popShow);
            }
          );
          break;
        case '测面':
          cesium.drawAreaMeasureGraphics(
            true,
            calculateId,
            (pos: any, val: any) => {
              console.log(pos, '>>>>>>>>>>', val);
              data.addPopInfo.position = pos;
              data.addPopInfo.measureValue = val;
              // 画完图形后打开弹窗
              data.addPopInfo.popShow = true;
            }
          );
          break;
        case '测高':
          cesium.drawTrianglesMeasureGraphics(
            calculateId,
            (pos: any, val: any) => {
              console.log(pos, '>>>>>>', val);
              data.addPopInfo.position = pos;
              data.addPopInfo.measureValue = val;
              // 画完图形后打开弹窗
              data.addPopInfo.popShow = true;
            }
          );
          break;
      }
    };

    // 清除测量画板
    const removeAllDraw = () => {
      cesium.measurementLayer.entities.removeAll();
    };

    // 新增弹窗按钮
    const addPopData = () => {
      console.log(movePoint);
      formRef.value
        .validate()
        .then((res: any) => {
          console.log(res);
          switch (data.addPopInfo.type) {
            case 'measure':
              let params = {
                type: data.addPopInfo.measureType,
                name: res.name,
                address: res.address,
                position: data.addPopInfo.position,
                measureValue: data.addPopInfo.measureValue
              };
              console.log(params);
              // 调用测量新增接口
              http
                .post('/node/api/measure/addData', params)
                .then((res: any) => {
                  console.log(res);
                  if (res.data.code == 200) {
                    message.success(res.data.msg);
                    // 重置属性,关闭弹窗
                    closeAddPop();
                  }
                });
              break;
            case 'point':
              console.log('添加点位');
              // let movePointEntities = movePoint;
              console.log(pointDataSource.get(res.iconLabel)?.entities);

              pointDataSource.get(res.iconLabel)?.entities.add(movePoint);
              closeAddPop();
              console.log(pointDataSource.get(res.iconLabel)?.entities);
              break;
          }
        })
        .catch((err: any) => {
          console.log('错误', err);
        });
    };

    // 关闭新增弹窗
    const closeAddPop = () => {
      data.addPopInfo.type = '';
      data.addPopInfo.popShow = false;
      formRef.value.resetFields();
      data.addPopInfo.title = '';
      data.addPopInfo.measureType = '';
      console.log(data.addPopInfo.popShow);
      pointDataSource.get('移动点位')?.entities.removeAll();
    };

    // 拖动新增图标
    const dragIconAdd = () => {
      const handlers = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
      // let iconNode = document.getElementById('point_icon') as any;
      // // 复制节点
      // let clonedNode = iconNode.cloneNode(true);
      // // 添加样式
      // clonedNode.style.width = '30px';
      // clonedNode.style.position = 'fixed';
      // clonedNode.style.zIndex = '999';
      // clonedNode.style.pointerEvents = 'none';
      // iconNode.parentNode.insertBefore(clonedNode, iconNode.nextSibling);
      // 添加图标
      let obj = {
        name: '移动点位',
        lon: 113.69444,
        lat: 27.94179,
        height: 15, // 图标距地图高度
        imgUrl: 'src/assets/img/视图.png',
        label: '标签名称-某某库',
        pointType: 'MOVEPOINT' // 将图标类型设置成移动图标，防止点击和悬浮弹窗
      };
      addMovePoint(obj);
      let ismove = true;
      handlers.setInputAction((movement: { position: Cesium.Cartesian2 }) => {
        // 如果已新增图标，则断地图移动监听
        if (!ismove) return;
        const cartesian = cesium.getCatesian3PX((movement as any).endPosition);
        // console.log(cartesian, '>>>>>>>.', movePoint);
        // console.log(
        //   cesium.transformCartesianToWGS84(cartesian as Cesium.Cartesian3)
        // );
        if (cartesian) movePoint.position = cartesian;
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      handlers.setInputAction((movement: { position: Cesium.Cartesian2 }) => {
        if (ismove) {
          var ray = viewer.camera.getPickRay(movement.position);
          var earthPosition = viewer.scene.globe.pick(
            ray as Cesium.Ray,
            viewer.scene
          );
          console.log(
            Cesium.defined(earthPosition),
            cesium.transformCartesianToWGS84(earthPosition as Cesium.Cartesian3)
          );
          let pos = cesium.transformCartesianToWGS84(
            earthPosition as Cesium.Cartesian3
          );
          if (Cesium.defined(earthPosition)) {
            // 中断地图移动监听
            ismove = false;
            if (pos) {
              // 清除复制的节点
              // clonedNode.remove();
              data.addPopInfo.lon = pos?.x;
              data.addPopInfo.lat = pos?.y;
              data.addPopInfo.popShow = true;
              data.addPopInfo.type = 'point';
            }
          }
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    };

    // flyto方法
    const flyto = (
      lon: number,
      lat: number,
      height = 70,
      heading = -25,
      pitch = -15
    ) => {
      viewer.camera.flyTo({
        // 初始化相机经纬度
        destination: Cesium.Cartesian3.fromDegrees(lon, lat, height),
        orientation: {
          heading: Cesium.Math.toRadians(heading),
          pitch: Cesium.Math.toRadians(pitch),
          roll: 0
        }
      });
    };

    // 跟随鼠标移动点位添加
    const addMovePoint = async (item: any) => {
      console.log(item);
      // const customDataSource = new Cesium.CustomDataSource(item.name);
      // await viewer.dataSources.add(customDataSource);
      movePoint = pointDataSource.get(item.name)?.entities.add({
        show: true,
        id: item.name + '-' + getUUID(),
        name: { ...item, TYPE: item.pointType },
        billboard: {
          // image: './iconImg/textImg.png', // 默认图标
          image: item.imgUrl, // 默认图标
          scale: 1.0, // 图标缩放比例
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM, // 将广告牌底部与位置对齐
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          disableDepthTestDistance: Number.POSITIVE_INFINITY, // 漂移bug Number.POSITIVE_INFINITY
          distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
            0.0,
            1000000.0
          ),
          scaleByDistance: new Cesium.NearFarScalar(1e2, 1, 1e4, 0.2)
        },
        label: {
          text: item.label, // 显示的文字
          font: '16px Helvetica', // 字体设置
          fillColor: Cesium.Color.WHITE,
          outlineColor: Cesium.Color.SKYBLUE,
          outlineWidth: 2,
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          pixelOffset: new Cesium.Cartesian2(0, -45), // 文字偏移量
          disableDepthTestDistance: Number.POSITIVE_INFINITY,
          scaleByDistance: new Cesium.NearFarScalar(1e2, 1, 2e3, 0.0)
        },
        position: Cesium.Cartesian3.fromDegrees(item.lon, item.lat, item.height) // 手动点位
      });
    };

    // 拖拽组件聚焦问题解决
    const clickHandle = (e: any) => {
      if (e.target.nodeName === 'INPUT' || e.target.nodeName === 'TEXTAREA') {
        e.target.focus();
      }
    };

    // 车路线图添加
    let linePoints = [] as any[];
    var carEntity = null as any;
    var lineEntity = null as any;
    // let currentTime = 0;
    // const duration = 10; // 动画持续时间，单位秒
    // const speed = 1 / duration; // 每秒移动的距离比例
    const addCarPath = (id: string, imgUrl: string, boolean: boolean) => {
      if (carEntity) {
        console.log(carEntity);
        carEntity.show = boolean;
        lineEntity.show = boolean;
        return;
      }
      const startPoint = Cesium.Cartesian3.fromDegrees(113.6999, 27.94188, 15);
      const positions = [
        { x: 113.6999, y: 27.94188, z: 15 },
        { x: 113.69986, y: 27.94218, z: 15 },
        { x: 113.69955, y: 27.94291, z: 15 },
        { x: 113.69941, y: 27.94297, z: 15 },
        { x: 113.69882, y: 27.94344, z: 15 },
        { x: 113.6976, y: 27.94352, z: 15 },
        { x: 113.69692, y: 27.94335, z: 15 }
      ];

      let arrData = [] as any[];
      positions.forEach((item: any) => {
        arrData.push(item.x);
        arrData.push(item.y);
      });
      linePoints = Cesium.Cartesian3.fromDegreesArray(arrData);
      carEntity = viewer.entities.add({
        id,
        position: startPoint,
        billboard: {
          // image: './iconImg/textImg.png', // 默认图标
          image: imgUrl, // 默认图标
          scale: 0.3, // 图标缩放比例
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM, // 将广告牌底部与位置对齐
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          disableDepthTestDistance: Number.POSITIVE_INFINITY, // 漂移bug Number.POSITIVE_INFINITY
          // distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
          //   0.0,
          //   1000000.0
          // ),
          scaleByDistance: new Cesium.NearFarScalar(1e2, 1, 1e4, 0.2)
        }
        // model: {
        //   uri: 'path/to/your/car-model.glb',
        //   minimumPixelSize: 128
        // }
      });
      lineEntity = viewer.entities.add({
        polyline: {
          positions: linePoints,
          width: 5,
          material: Cesium.Color.RED.withAlpha(0.5),
          clampToGround: true,
          classificationType: Cesium.ClassificationType.BOTH // 线贴地
        }
      });

      const property = new Cesium.SampledProperty(Cesium.Cartesian3);
      // // 获取前10分钟的时间
      const tenMinutesAgo =
        dayjs().add(0, 'minute').format('YYYY-MM-DDTHH:mm:ss.00') + 'Z';
      // // 获取后10分钟的时间
      const tenMinutesLater =
        dayjs().add(0.3*(positions.length-1), 'minute').format('YYYY-MM-DDTHH:mm:ss.00') + 'Z';
      console.log(tenMinutesAgo, '>>>>>>', tenMinutesLater);
      // 对应标点路径
      positions.forEach((item: any, index: number) => {
        let time = 0.3 * index;
        let MinutesAgo =
          dayjs().add(time, 'minute').format('YYYY-MM-DDTHH:mm:ss.00') + 'Z';
          console.log(MinutesAgo)
        property.addSample(
          Cesium.JulianDate.fromIso8601(MinutesAgo),
          new Cesium.Cartesian3(item.x, item.y, item.z)
        );
      });
      property.addSample(
        Cesium.JulianDate.fromIso8601(tenMinutesAgo),
        new Cesium.Cartesian3(113.6999, 27.94188, 15)
      );
      // console.log(carEntity.properties)
      carEntity.property = property;
      var newTime = Cesium.JulianDate.fromIso8601(tenMinutesAgo);
      viewer.clock.currentTime = newTime;
      viewer.clock.multiplier = 1; // 设置时钟速度
      viewer.clock.shouldAnimate = true; // 如果需要自动播放动画
      viewer.clock.startTime = Cesium.JulianDate.fromIso8601(tenMinutesAgo);
      viewer.clock.stopTime = Cesium.JulianDate.fromIso8601(tenMinutesLater);
      // 设置Clock的循环模式
      viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP; // 循环播放
      animateIcon();
    };
    // setTimeout(() => {
    //   viewer.clock.onTick.addEventListener(clock11 => {
    //     console.log(clock11, '*-*--------------');
    //   })
    // }, 5000)

    function animateIcon() {
      viewer.clock.onTick.addEventListener((clock) => {
        // console.log(clock.currentTime, '*-*--------------');
        // 将JulianDate转换为ISO 8601格式的字符串
        const iso8601String = Cesium.JulianDate.toIso8601(clock.currentTime); // ISO 8601格式('2024-05-22T20:00:00.00Z')
        carEntity.position = cesium.transformWGS84ToCartesian(
          carEntity.property.getValue(
            Cesium.JulianDate.fromIso8601(iso8601String)
          ),
          15
        );
      });
      // currentTime += Cesium.JulianDate.secondsDifference(
      //   new Cesium.JulianDate(),
      //   new Cesium.JulianDate(currentTime)
      // );
      // console.log(linePoints);
      // carEntity.position = carEntity.properties.fuel_remaining.getValue(
      //   viewer.clock.currentTime
      // )

      // let dataTime =
      //   getTenMinutesAgoPlusTenSeconds().format('YYYY-MM-DDTHH:mm:ss.00') + 'Z';
      // console.log(dataTime);
      // carEntity.position = cesium.transformWGS84ToCartesian(
      //   carEntity.tttt.getValue(Cesium.JulianDate.fromIso8601(dataTime)),
      //   15
      // );
      // console.log(
      //   carEntity.tttt.getValue(Cesium.JulianDate.fromIso8601(dataTime))
      // );
      // console.log(cesium.transformWGS84ToCartesian(carEntity.tttt.getValue(Cesium.JulianDate.fromIso8601('2024-05-22T20:00:00.00Z')),15))
      // console.log(carEntity.tttt.getValue(Cesium.JulianDate.fromIso8601('2024-04-21T17:00:00.00Z')), '[****************]', viewer.clock.currentTime);

      // const t = Math.min(currentTime * speed, 1); // 归一化时间

      // // 使用Cesium的插值函数计算当前位置
      // console.log(linePoints);
      // const currentPosition = Cesium.Cartesian3.lerp(
      //   linePoints[0],
      //   linePoints[linePoints.length - 1],
      //   t,
      //   new Cesium.Cartesian3()
      // );

      // // 更新图标位置
      // carEntity.position = currentPosition;

      // 如果图标还没有到达终点，则继续动画
      // if (t < 1) {
      //   requestAnimationFrame(animateIcon);
      // }
      // requestAnimationFrame(animateIcon);
    }

    return {
      ...toRefs(data),
      drag,
      cesiumContainerRef,
      formRef,
      addPoint,
      addProductPoint,
      addColorSegment,
      addArea,
      addCarPath,
      flyto,
      calculateTool,
      removeAllDraw,
      addPopData,
      closeAddPop,
      dragIconAdd,
      clickHandle
    };
  }
};
</script>
<style scoped lang="less">
#cesiumContainer {
  width: 100vw;
  height: 100vh;
  position: absolute;
}

.chen-infomationAlert {
  position: absolute;
  width: 360px;
  color: #fff;
  pointer-events: none;

  .bgTop {
    background: url('../assets/img/frame-top.png') no-repeat center;
    background-size: 100% 100%;
    height: 60px;
  }

  .bgCenter {
    background: url('../assets/img/frame-center.png') no-repeat center;
    background-size: 100% 100%;
    margin: -16px 8px;
    padding: 0 16px;

    :deep(p) {
      font-size: 15px;
      width: 100%;
      white-space: pre-wrap;
      text-shadow: 0 0 10px rgb(0, 198, 224), 0 0 10px rgb(0, 155, 198),
        0 0 30px rgb(14, 139, 174), 0 0 40px rgb(0, 129, 164);
      display: flex;
      flex-wrap: wrap;
      justify-content: flex-start;
      align-items: center;

      span {
        color: #fff;
        text-shadow: none;
        margin: 3px 12px;
      }
    }
  }

  .bgBottom {
    background: url('../assets/img/frame-bottom.png') no-repeat center;
    background-size: 100% 100%;
    height: 48px;
  }
}

.chen-infomationPop {
  position: absolute;
  width: 360px;
  color: #fff;
  pointer-events: none;
  z-index: 999;

  .bgTop {
    background: url('../assets/img/popTop.png') no-repeat center;
    background-size: 100% 100%;
    height: 50px;
    position: relative;
    cursor: move;
    pointer-events: auto;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    padding: 6px 88px 6px 6px;

    span {
      font-size: 15px;
      font-weight: bold;
      text-shadow: 0 0 10px rgb(0, 198, 224), 0 0 10px rgb(0, 155, 198),
        0 0 30px rgb(14, 139, 174), 0 0 40px rgb(0, 129, 164);
    }

    .close {
      position: absolute;
      top: 0;
      right: 1%;
      color: #fff;
      font-size: 20px;
      padding: 5px;
      text-align: center;
      cursor: pointer;
      transition: all 0.3s ease-in-out;
      transform-origin: center 54%;
      text-shadow: none;

      &:hover {
        transform: rotate(90deg) scale(1.2);
      }
    }
  }

  .bgCenter {
    background: url('../assets/img/popCenter.png') no-repeat center;
    background-size: 100% 100%;
    padding: 0 5px;

    :deep(iframe) {
      width: 100%;
      height: 360px;
      border: none;
      pointer-events: auto;
      background: #fff;
      border-radius: 6px;
    }

    .content {
      padding: 1px 5px;
      p {
        padding: 3px 0;
      }
      video {
        width: 100%;
        aspect-ratio: 2 / 1;
      }
    }
  }

  .bgBottom {
    background: url('../assets/img/popBottom.png') no-repeat center;
    background-size: 100% 100%;
    height: 12px;
  }
}

.pointInfo {
  position: fixed;
  z-index: 9;
  bottom: 30px;
  left: 23%;
  z-index: 9;
  display: flex;
  justify-content: space-around;
  align-items: center;

  span {
    font-size: 16px;
    margin-left: 30px;
    font-weight: 700;
    color: aliceblue;
  }
}

.addInfoPop {
  position: absolute;
  // top: 40%;
  // left: 50%;
  width: 600px;
  color: white;
  .dragBg {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 50px;
    background: floralwhite;
  }
  .close {
    position: absolute;
    top: 0;
    right: 1%;
    color: #fff;
    font-size: 30px;
    padding: 5px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease-in-out;
    transform-origin: center 54%;
    text-shadow: none;

    &:hover {
      transform: rotate(90deg) scale(1.2);
    }
  }
  .popTop {
    width: 100%;
    height: 50px;
    background: url('../assets/img/popTop.png') center no-repeat;
    background-size: 100% 100%;
    display: flex;
    justify-content: left;
    align-items: center;
    span {
      margin-top: -10px;
      margin-left: 10px;
      letter-spacing: 3px;
      font-weight: bold;
    }
  }
  .popCenter {
    width: 100%;
    height: 70%;
    background: url('../assets/img/popCenter.png') center no-repeat;
    background-size: 100% 100%;
    overflow-y: auto;
    overflow-x: hidden;
    :deep(.ant-form) {
      display: flex;
      flex-wrap: wrap;
      padding: 3px 20px 0 10px;
      z-index: 9;
    }
    :deep(.ant-form-item-label > label) {
      color: white;
      margin-left: 10px;
    }
    :deep(.ant-form-item) {
      width: 50%;
      margin-bottom: 20px;
    }
    .selectIcon {
      :deep(.ant-select-item-option-content) {
        height: 30px;
      }
      .imageIcon {
        width: 20px;
        height: 25px;
      }
      span {
        margin-left: 5px;
        font-size: 16px;
      }
    }
    :deep(.ant-select) {
      &::placeholder {
        color: rgb(255, 7, 7);
      }
    }
    .lang_input {
      width: 100%;
    }
    .ant-input {
      margin-right: 10px;
      line-height: 0;
      &::placeholder {
        color: rgba(169, 169, 169, 0.6);
      }
    }
  }
  .popBottom {
    width: calc(100% + 1px);
    height: 50px;
    background: url('../assets/img/popBottom.png') center no-repeat;
    background-size: 100% 100%;
    display: flex;
    justify-content: right;
    align-items: center;
    button {
      background: rgba(0, 166, 255, 0.7);
      color: white;
      padding: 5px 20px;
      margin-right: 20px;
      border-color: rgba(0, 90, 158, 0.8);
      cursor: pointer;
    }
  }
}
</style>

